import ErrorLogModule from '@/store/modules/error-log'

export const globalErrorHandler = (
  err: Error,
  vm?: any,
  info?: string
): void => {
  ErrorLogModule.addErrorLog({
    err,
    info,
    url: window.location.href,
    date: new Date()
  })
  if (process.env.NODE_ENV !== 'production') {
    console.error('An Error Occurred!\n', err, info)
  }
}

const promiseErrorCatchHandler = (event: PromiseRejectionEvent): void => {
  globalErrorHandler(event.reason)

  event.preventDefault()
}

export const promiseErrorCatcher = {
  add: () => {
    window.addEventListener('unhandledrejection', promiseErrorCatchHandler)
  },
  remove: () => {
    window.removeEventListener('unhandledrejection', promiseErrorCatchHandler)
  }
}
